#import "LiveRoomViewController.h"
#import "VideoSession.h"
#import "VideoViewLayouter.h"
#import "KeyCenter.h"
#import "GiftView.h"
#define OPEN_TISDK 0
#import "TiUIView.h"
#import "TiSDKInterface.h"
#import "AGVideoPreProcessing.h"
@interface LiveRoomViewController () <AgoraRtcEngineDelegate,UIGestureRecognizerDelegate
, TiUIViewDelegate
>
@property (strong, nonatomic)  UILabel *roomNameLabel;
@property (strong, nonatomic)  UIView *remoteContainerView;
@property (strong, nonatomic)  UIButton *broadcastButton;
@property (strong, nonatomic)NSArray *sessionButtons;
@property (strong, nonatomic)  UIButton *audioMuteButton;
@property (strong, nonatomic)  UIButton *enhancerButton;
@property (strong, nonatomic) AgoraRtcEngineKit *rtcEngine;
@property (assign, nonatomic) BOOL isBroadcaster;
@property (assign, nonatomic) BOOL isMuted;
@property (assign, nonatomic) BOOL shouldEnhancer;
@property (strong, nonatomic) NSMutableArray<VideoSession *> *videoSessions;
@property (strong, nonatomic) VideoSession *fullSession;
@property (strong, nonatomic) VideoViewLayouter *viewLayouter;
@property(nonatomic, assign) BOOL meShowFull;
@property(nonatomic, strong) TiUIView *tiUIView;
@property(nonatomic, strong) TiSDKManager *tiSDKManager;
@end
@implementation LiveRoomViewController
- (BOOL)isBroadcaster {
    return self.clientRole == AgoraClientRoleBroadcaster;
}
- (VideoViewLayouter *)viewLayouter {
    if (!_viewLayouter) {
        _viewLayouter = [[VideoViewLayouter alloc] init];
    }
    return _viewLayouter;
}
- (void)setClientRole:(AgoraClientRole)clientRole {
    _clientRole = clientRole;
    if (self.isBroadcaster) {
        self.shouldEnhancer = YES;
    }
    [self updateButtonsVisiablity];
}
- (void)setIsMuted:(BOOL)isMuted {
    _isMuted = isMuted;
    [self.rtcEngine muteLocalAudioStream:isMuted];
    [self.audioMuteButton setImage:[UIImage imageNamed:(isMuted ? @"btn_mute_cancel" : @"btn_mute")] forState:UIControlStateNormal];
}
- (void)setVideoSessions:(NSMutableArray<VideoSession *> *)videoSessions {
    _videoSessions = videoSessions;
    if (self.remoteContainerView) {
        [self updateInterfaceWithAnimation:YES];
    }
}
- (void)setFullSession:(VideoSession *)fullSession {
    _fullSession = fullSession;
    if (self.remoteContainerView) {
        [self updateInterfaceWithAnimation:NO];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.videoSessions = [[NSMutableArray alloc] init];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doDoubleTapped:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    self.roomNameLabel.text = self.roomName;
    [self setupUI];
    [self updateButtonsVisiablity];
    [self loadAgoraKit];
    if(OPEN_TISDK)
    {
        NSString* key = @"6330b68ec82844848cdecc593df4e9ea";
        [TiSDK init:key];
        self.tiSDKManager = [[TiSDKManager alloc]init];
        self.tiUIView = [[TiUIView alloc]initTiUIViewWith:self.tiSDKManager delegate:self superView:self.view];
        self.tiUIView.isClearOldUI = NO;
        [self.tiUIView createTiUIView];
        [AGVideoPreProcessing registerVideoPreprocessing: self.rtcEngine];
    }
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    NSLog(@"点击的class  %@",[touch.view class]);
    if ([[touch.view className] isEqualToString:@"AgoraVideoRenderIosView"] || touch.view.tag == 71730) {
        return YES;
    }
    return NO; 
}
-(void)setupUI
{
    _remoteContainerView = [[UIView alloc] init];
    _remoteContainerView.frame = self.view.bounds;
    [self.view addSubview:_remoteContainerView];
}
- (void)doSwitchCameraPressed{
    [self.rtcEngine switchCamera];
}
- (void)doMutePressed{
    self.isMuted = !self.isMuted;
}
- (IBAction)doBroadcastPressed:(UIButton *)sender {
    if (self.isBroadcaster) {
        self.clientRole = AgoraClientRoleAudience;
        if (self.fullSession.uid == 0) {
            self.fullSession = nil;
        }
    } else {
        self.clientRole = AgoraClientRoleBroadcaster;
    }
    [self.rtcEngine setClientRole:self.clientRole];
    [self updateInterfaceWithAnimation:YES];
    [self sendCallMessage];
}
-(void)sendCallMessage
{
}
-(void)clickBackView
{
}
- (IBAction)doDoubleTapped:(UITapGestureRecognizer *)sender {
    [self clickBackView];
    _meShowFull = !_meShowFull;
    if(_meShowFull)
    {
        self.fullSession = self.videoSessions[0];
    }
    else
    {
        self.fullSession = self.videoSessions[1];
    }
}
- (void)doLeavePressed{
    [self leaveChannel];
}
- (void)updateButtonsVisiablity {
    [self.broadcastButton setImage:[UIImage imageNamed:self.isBroadcaster ? @"btn_join_cancel" : @"btn_join"] forState:UIControlStateNormal];
    for (UIButton *button in self.sessionButtons) {
        button.hidden = !self.isBroadcaster;
    }
}
- (void)leaveChannel {
    [self setIdleTimerActive:YES];
    [self.rtcEngine setupLocalVideo:nil];
    [self.rtcEngine leaveChannel:nil];
    if (self.isBroadcaster) {
        [self.rtcEngine stopPreview];
    }
    for (VideoSession *session in self.videoSessions) {
        [session.hostingView removeFromSuperview];
    }
    [self.videoSessions removeAllObjects];
    if(OPEN_TISDK)
    {
        [self.tiUIView releaseTiUIView];
        [self.tiSDKManager destroy];
        [AGVideoPreProcessing deregisterVideoPreprocessing: self.rtcEngine];
    }
    if ([self.delegate respondsToSelector:@selector(liveVCNeedClose:)]) {
        [self.delegate liveVCNeedClose:self];
    }
}
- (void)setIdleTimerActive:(BOOL)active {
    [UIApplication sharedApplication].idleTimerDisabled = !active;
}
- (void)alertString:(NSString *)string {
    if (!string.length) {
        return;
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)updateInterfaceWithAnimation:(BOOL)animation {
    if (animation) {
        [UIView animateWithDuration:0.3 animations:^{
            [self updateInterface];
            [self.view layoutIfNeeded];
        }];
    } else {
        [self updateInterface];
    }
}
- (void)updateInterface {
    NSArray *displaySessions;
    if (!self.isBroadcaster && self.videoSessions.count) {
        displaySessions = [self.videoSessions subarrayWithRange:NSMakeRange(1, self.videoSessions.count - 1)];
    } else {
        displaySessions = [self.videoSessions copy];
    }
    [self.viewLayouter layoutSessions:displaySessions fullSession:self.fullSession inContainer:self.remoteContainerView];
    [self setStreamTypeForSessions:displaySessions fullSession:self.fullSession];
}
- (void)setStreamTypeForSessions:(NSArray<VideoSession *> *)sessions fullSession:(VideoSession *)fullSession {
    if (fullSession) {
        for (VideoSession *session in sessions) {
            [self.rtcEngine setRemoteVideoStream:session.uid type:(session == self.fullSession ? AgoraVideoStreamTypeHigh : AgoraVideoStreamTypeLow)];
        }
    } else {
        for (VideoSession *session in sessions) {
            [self.rtcEngine setRemoteVideoStream:session.uid type:AgoraVideoStreamTypeHigh];
        }
    }
}
- (void)addLocalSession {
    VideoSession *localSession = [VideoSession localSession];
    [self.videoSessions addObject:localSession];
    [self.rtcEngine setupLocalVideo:localSession.canvas];
    [self updateInterfaceWithAnimation:YES];
}
- (VideoSession *)fetchSessionOfUid:(NSUInteger)uid {
    for (VideoSession *session in self.videoSessions) {
        if (session.uid == uid) {
            return session;
        }
    }
    return nil;
}
- (VideoSession *)videoSessionOfUid:(NSUInteger)uid {
    VideoSession *fetchedSession = [self fetchSessionOfUid:uid];
    if (fetchedSession) {
        return fetchedSession;
    } else {
        VideoSession *newSession = [[VideoSession alloc] initWithUid:uid];
        [self.videoSessions addObject:newSession];
        [self updateInterfaceWithAnimation:YES];
        return newSession;
    }
}
- (void)loadAgoraKit {
    self.rtcEngine = [AgoraRtcEngineKit sharedEngineWithAppId:[KeyCenter AppId] delegate:self];
    [self.rtcEngine enableWebSdkInteroperability:YES];
    [self.rtcEngine setChannelProfile:AgoraChannelProfileLiveBroadcasting];
    [self.rtcEngine enableDualStreamMode:YES];
    [self.rtcEngine enableVideo];
    [self.rtcEngine setVideoProfile:self.videoProfile swapWidthAndHeight:YES];
    [self.rtcEngine setClientRole:self.clientRole];
    if (self.isBroadcaster) {
        [self.rtcEngine startPreview];
    }
    [self addLocalSession];
    int code = [self.rtcEngine joinChannelByToken:nil channelId:self.roomName info:nil uid:0 joinSuccess:^(NSString * _Nonnull channel, NSUInteger uid, NSInteger elapsed) {
    }];
    if (code == 0) {
        [self setIdleTimerActive:NO];
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Join channel failed: %d", code]);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertString:[NSString stringWithFormat:@"Join channel failed: %d", code]];
        });
    }
    if (self.isBroadcaster) {
        self.shouldEnhancer = YES;
    }
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
    if(uid == 1)
    {
#ifdef DEBUG
#endif
        return;
    }
    VideoSession *userSession = [self videoSessionOfUid:uid];
    [self.rtcEngine setupRemoteVideo:userSession.canvas];
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine firstLocalVideoFrameWithSize:(CGSize)size elapsed:(NSInteger)elapsed {
    if (self.videoSessions.count) {
        [self updateInterfaceWithAnimation:NO];
    }
}
- (int)enableWebSdkInteroperability:(BOOL)enabled
{
    return 1;
}
-(void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraUserOfflineReason)reason
{
    if(uid != 1)
    {
        VideoSession *deleteSession;
        for (VideoSession *session in self.videoSessions) {
            if (session.uid == uid) {
                deleteSession = session;
            }
        }
        if (deleteSession) {
            [self.videoSessions removeObject:deleteSession];
            [deleteSession.hostingView removeFromSuperview];
            [self updateInterfaceWithAnimation:YES];
            if (deleteSession == self.fullSession) {
                self.fullSession = nil;
            }
        }
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    _meShowFull = NO;
    [super viewWillDisappear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}
-(void)dealloc
{
    [self.tiSDKManager destroy];
}
-(void)isPopMY:(BOOL)isPop
{
}
-(void)didTiUISwitch:(BOOL)ispop
{
    [self isPopMY:ispop];
}
@end
